<template>
  <div class="houses-container">
    <!-- 页面标题 -->
    <div class="page-header">
      <div class="header-content">
        <h2 class="title">房源列表</h2>
        <!-- 我的订单按钮固定在右上角 -->
        <div class="fixed-right-btn">
          <el-button
              type="primary"
              @click="goToMyOrders"
              class="my-orders-btn"
          >
            我的订单
          </el-button>
        </div>
      </div>
    </div>

    <!-- 搜索栏 -->
    <div class="search-container">
      <el-input
          v-model="searchQuery"
          placeholder="搜索房源标题/ID/地址"
          clearable
          @clear="handleSearch"
          @keyup.enter="handleSearch"
          class="search-bar"
      >
        <template #append>
          <el-button @click="handleSearch">
            <el-icon><search /></el-icon>
          </el-button>
        </template>
      </el-input>
    </div>


    <!-- 房源列表（居中容器） -->
    <div class="houses-list-center">
      <div class="houses-list">
        <div v-if="loading" class="loading-container">
          <el-icon class="loading-icon"><loading /></el-icon>
          <span>加载中...</span>
        </div>

        <div v-else-if="houses.length === 0" class="empty-container">
          <el-empty description="暂无房源数据" />
        </div>

        <div v-else class="house-cards horizontal-scroll">
          <el-card
              v-for="house in filteredHouses"
              :key="house.houseid"
              class="house-card"
              shadow="hover"
              @click="handleViewDetails(house)"
          >
            <div class="card-content">
              <!-- 房源封面图 -->
              <div class="house-image">
                <el-image
                    style="width: 100%; height: 180px"
                    :src="getCoverImage(house.images)"
                    fit="cover"
                    :preview-src-list="getAllImages(house.images)"
                    hide-on-click-modal
                >
                  <template #error>
                    <div class="image-error">
                      <el-icon><picture /></el-icon>
                      <span>暂无图片</span>
                    </div>
                  </template>
                </el-image>
              </div>

              <!-- 房源基本信息 -->
              <div class="house-info">
                <h3 class="house-title">{{ house.title }}</h3>
                <div class="house-price">
                  <span class="price">{{ house.price }}元/月</span>
                  <span class="unit-price" v-if="house.area">
                    {{ calculateUnitPrice(house.price, house.area) }}元/㎡·月
                  </span>
                </div>
                <div class="house-meta">
                  <span>{{ house.room_type }} | {{ house.area }}㎡ | {{ house.orientation }}</span>
                </div>
                <div class="house-address">
                  <el-icon><location /></el-icon>
                  <span>{{ formatAddress(house.address) }}</span>
                </div>
                <div class="house-facilities">
                  <el-tag
                      v-for="(value, key) in house.facility"
                      v-if="value"
                      :key="key"
                      size="small"
                      class="facility-tag"
                  >
                    {{ facilityLabels[key] }}
                  </el-tag>
                </div>
              </div>
            </div>
          </el-card>
        </div>
      </div>
    </div>
  </div>
</template>



<script setup>
// 此处代码与原组件完全一致，无需修改
import { ref, computed, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import { Search, Picture, Loading, Location } from '@element-plus/icons-vue'
import axios from 'axios'
import { useRouter } from 'vue-router'

const router = useRouter()

// 搜索和分页相关
const searchQuery = ref('')
const currentPage = ref(1)
const pageSize = ref(10)
const totalHouses = ref(0)

// 房源数据
const houses = ref([])
const loading = ref(false)

// 设施标签映射
const facilityLabels = {
  has_lift: '电梯',
  has_parking: '停车位',
  has_wifi: 'WiFi',
  has_kitchen: '厨房',
  has_washer: '洗衣机',
  has_ac: '空调',
  has_heating: '暖气',
  has_tv: '电视'
}


// 跳转到我的订单页面
const goToMyOrders = () => {
  router.push({ name: 'my-order' }) // 确保路由名称匹配
}

// 计算属性 - 过滤房源
const filteredHouses = computed(() => {
  if (!searchQuery.value) return houses.value
  const query = searchQuery.value.toLowerCase()
  return houses.value.filter(house =>
      house.title.toLowerCase().includes(query) ||
      String(house.houseid).includes(query)
  )
})

// 获取房源列表
const fetchHouses = async () => {
  loading.value = true
  try {
    const params = {
      page: currentPage.value,
      per_page: pageSize.value
    }

    const apiUrl = searchQuery.value.trim()
        ? '/api/houses/search'
        : '/api/houses'

    if (searchQuery.value.trim()) {
      params.keyword = searchQuery.value.trim()
    }

    const response = await axios.get(apiUrl, { params })

    if (response.data.code === 0) {
      houses.value = response.data.data.houses.map(house => ({
        ...house,
        houseid: Number(house.houseid) || 0
      }))
      totalHouses.value = response.data.data.total

      houses.value.forEach(house => {
        if (!house.images?.gallery) {
          house.images = house.images || {}
          house.images.gallery = []
        }
      })
    } else {
      handleApiError(response.data)
    }
  } catch (error) {
    handleNetworkError(error)
  } finally {
    loading.value = false
  }
}

// 图片处理
const getCoverImage = (images) => {
  return images?.cover?.image_url || images?.gallery?.[0]?.image_url || ''
}

const getAllImages = (images) => {
  const gallery = images?.gallery || []
  const cover = images?.cover?.image_url ? [images.cover.image_url] : []
  return [...cover, ...gallery.map(img => img.image_url)].filter(Boolean)
}

// 地址格式化
const formatAddress = (address) => {
  if (!address) return ''
  return `${address.province || ''}${address.city || ''}${address.district || ''}${address.street || ''}`
}

// 计算单价
const calculateUnitPrice = (price, area) => {
  if (!price || !area || area === 0) return '0'
  return (price / area).toFixed(2)
}

// 错误处理
const handleApiError = (errorData) => {
  const errorMsg = errorData.extra_msg || errorData.msg || '请求失败'
  ElMessage.error(errorMsg)
}

const handleNetworkError = (error) => {
  if (error.response) {
    ElMessage.error(`服务器错误: ${error.response.status}`)
  } else if (error.request) {
    ElMessage.error('请求超时，请检查网络连接')
  } else {
    ElMessage.error(`请求错误: ${error.message}`)
  }
}

// 搜索和分页处理
const handleSearch = () => {
  currentPage.value = 1
  fetchHouses()
}

const handleSizeChange = (newSize) => {
  pageSize.value = newSize
  currentPage.value = 1
  fetchHouses()
}

const handlePageChange = () => {
  fetchHouses()
}


// 清空搜索
const handleClearSearch = () => {
  searchQuery.value = ''
  currentPage.value = 1
  fetchHouses()
}

// 查看详情 - 修复后的版本
const handleViewDetails = (house) => {
  if (!house?.houseid) {
    ElMessage.error('无效的房源ID');
    return;
  }

  router.push({
    name: 'RhouseDetail',
    params: {
      houseid: house.houseid // 使用全小写
    }
  }).catch(err => {
    if (!err.message.includes('Avoided redundant navigation')) {
      ElMessage.error('导航失败');
    }
  });
}

// 初始化
onMounted(() => {
  fetchHouses()
})
</script>

<style scoped>
.houses-container {
  padding: 20px;
  min-height: 100vh;
  position: relative; /* 为固定定位提供参考 */
}

.page-header {
  margin-bottom: 20px;
  display: block; /* 取消flex布局，方便按钮定位 */
  position: relative;
}

.header-content {
  max-width: 1200px;
  margin: 0 auto; /* 标题居中 */
  display: flex;
  justify-content: space-between;
  align-items: center;
}

/* 我的订单按钮固定在右上角 */
.fixed-right-btn {
  position: absolute;
  top: 20px;
  right: 20px;
}

.title {
  font-size: 24px;
  font-weight: 500;
  color: #333;
  text-align: left; /* 标题左对齐 */
}

.search-container {
  margin-bottom: 20px;
}

/* 房源列表居中容器 */
.houses-list-center {
  max-width: 1200px;
  margin: 0 auto;
}

.houses-list {
  margin-top: 20px;
  overflow-x: auto;
}

/* 其他样式保持不变 */
/* 横向滚动布局 */
.house-cards {
  display: flex;
  gap: 20px;
  padding: 10px 0;
  min-width: max-content;
}

.horizontal-scroll {
  overflow-x: auto;
  white-space: nowrap;
}

.house-card {
  cursor: pointer;
  transition: transform 0.3s;
  display: inline-flex;
  min-width: 280px;
  max-width: 280px;
  margin-right: 20px;
}

.house-card:last-child {
  margin-right: 0;
}

.house-card:hover {
  transform: translateY(-5px);
}

.card-content {
  display: flex;
  flex-direction: column;
  height: 100%;
  width: 280px;
}

/* 滚动条样式 */
.houses-list::-webkit-scrollbar {
  height: 6px;
  background-color: #f1f1f1;
}

.houses-list::-webkit-scrollbar-thumb {
  background-color: #c1c1c1;
  border-radius: 3px;
}

/* 响应式调整 */
@media (max-width: 1024px) {
  .house-card {
    min-width: 240px;
    max-width: 240px;
  }

  .card-content {
    width: 240px;
  }
}

@media (max-width: 768px) {
  .house-card {
    min-width: 100%;
    max-width: 320px;
    margin: 0 auto 20px;
    display: block;
  }

  .house-cards {
    flex-wrap: wrap;
    justify-content: center;
  }
}
</style>